/**
 * Description: 
 * How to use an iterator on lat/lon/values and query the bitmap for missing values.
 * (rather than compare each value with the missingValue key)
 * 
 * 如何在 lat/lon/values 上使用迭代器并查询位图以查找缺失值
 * (而不是将每个值与 missingValue 键进行比较)
 */

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "eccodes.h"

int sfx_grib_iterator_bitmap()
{
    int err = 0;
    int n   = 0;

    // char* filename = "d:\\temp\\era5-levels-members.grib";
    char* filename = "d:/sfxData/ECMWF/eccodes_test_data/simple_bitmap.grib";
    FILE* in       = fopen(filename, "rb");

    double lat, lon, value;
    long bitmapPresent = 0;
    size_t bmp_len = 0, values_len = 0;
    long* bitmap         = NULL;
    double* values       = NULL;
    codes_handle* h      = NULL;
    codes_iterator* iter = NULL;

    // loop message
    while ((h = codes_handle_new_from_file(0, in, PRODUCT_GRIB, &err)) != NULL) {
        //
        if (err != CODES_SUCCESS) CODES_CHECK(err, 0);

        CODES_CHECK(codes_get_long(h, "bitmapPresent", &bitmapPresent), 0);
        if (bitmapPresent) {
            CODES_CHECK(codes_get_size(h, "bitmap", &bmp_len), 0);
            bitmap = (long*)malloc(bmp_len * sizeof(long));
            CODES_CHECK(codes_get_long_array(h, "bitmap", bitmap, &bmp_len), 0);
            printf("Bitmap is present. Num = %zu\n", bmp_len);
        }
        // Sanity check. Number of values must match number in bitmap
        CODES_CHECK(codes_get_size(h, "values", &values_len), 0);
        values = (double*)malloc(values_len * sizeof(double));
        CODES_CHECK(codes_get_double_array(h, "values", values, &values_len), 0);

        // 比较两种方法的结果
        if (bitmapPresent) {
            assert(values_len == bmp_len);
        }

        // A new iterator on lat/lon/values is created from the message handle h
        iter = codes_grib_iterator_new(h, 0, &err);
        if (err != CODES_SUCCESS) CODES_CHECK(err, 0);

        n = 0;
        // Loop on all the lat/lon/values. Only print non-missing values
        while (codes_grib_iterator_next(iter, &lat, &lon, &value)) {
            // Consult bitmap to see if the n'th value is missing (查看位图以查看是否缺少第 n 个值)
            int is_missing_val = (bitmapPresent && bitmap[n] == 0);
            if (!is_missing_val) {
                // 打印非缺失值 (测试时数据太多,可屏蔽下面一行运行)
                printf("- %d - lat=%f lon=%f value=%f\n", n, lat, lon, value);
            }
            n++;
        }

        // Check number of elements in iterator matches value count
        assert(n == values_len);

        // free memory
        codes_grib_iterator_delete(iter);
        codes_handle_delete(h);
    }

    fclose(in);
    return 0;
}
